package com.acme.bankapp.service.bank.network;

import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Transport implements Closeable {
    private ObjectOutputStream out;
    private ObjectInputStream in;

    public Transport(Socket socket) throws TransportException {
        try {
            out = new ObjectOutputStream(socket.getOutputStream());
            in = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            throw new TransportException(e);
        }
    }

    public void sendMessage(String message) throws TransportException {
        try {
            out.writeObject(message);
            out.flush();
        } catch (IOException e) {
            throw new TransportException(e);
        }
    }

    public String receiveMessage() throws TransportException {
        try {
            return (String) in.readObject();
        } catch (ClassNotFoundException | IOException e) {
            throw new TransportException(e);
        }
    }

    @Override
    public void close() throws TransportException {
        try {
            in.close();
            out.close();
        } catch (IOException e) {
            throw new TransportException(e);
        }
    }
}

